import { _decorator, color, Color, Component, director, EventTouch, find, Input, Label, math, Node, Sprite, tween, UITransform, Vec2, Vec3 } from 'cc';
import { PinAction } from './PinAction';

import { AudioMgr } from './AudioMgr';
import { Clips, events, FishEvent   } from './Enums';
import { Tools } from './Tools';
import { Global } from './Global';
import { CatColorRules } from './CatColorRules';
import { HoleAction } from './HoleAction';
import { CannonControl } from './fish/CannonControl';
import { LayerCatAction } from './LayerCatAction';
import { gameMgr } from '../gameMgr';
import { LevelAction } from './LevelAction';
const { ccclass, property } = _decorator;

@ccclass('CatAction')
export class CatAction extends Component {
    cat_color: any;
    default_position: Readonly<Vec3>;
    defalut_lock: boolean = false;//默认不锁
    @property({ type: Node })
    lock: Node;
    isLocked: boolean = false;

    indexSpr = 0;

    onLoad(): void {
        //get default position
        this.default_position = this.node.getPosition().clone();
        //显示锁头
        this.defalut_lock = this.lock.active;
    }

    start() {

        this.node.on(Input.EventType.TOUCH_START, this.touch_start, this);
    }

    init_cat() {
        // console.log("init>>>>>>> slot>>>>>>>>>defalut_lock>>",this.defalut_lock,this.isLocked);
        this.set_lock_unlock(this.defalut_lock);
        this.clear_pins();
        // console.log("init slot,",this.isLocked);
        //console.log(this.default_position)

        this.node.setPosition(this.default_position.x, this.default_position.y);
        if (this.isLocked) {
            //默认有锁定的，让其出现在默认位置
            return;
        }
        //set slot color
        // 改 25.7.9.18.11 初始化
        // this.cat_color = CatColorRules.get_next_cat_color(CatColorRules.r_0());
        // console.log("Cat ",this.node.name)

        this.cat_color = LayerCatAction.Inst.batteryBoxs[0];
        LayerCatAction.Inst.batteryBoxs.splice(0,1)


        console.log("仓：",LayerCatAction.Inst.batteryBoxs)

        if (!this.cat_color) {
            //没有颜色，了。
            return;
        }
        //console.log(this.cat_color)
        
        //set color
        this.set_img(this.cat_color, 255);
    }

    get_cat_color(): any {
        return this.cat_color;
    }

    set_lock_unlock(l: boolean) {
        if (l) {
            //lock
            this.isLocked = true;
            //隐藏 hole
            this.node.children.forEach(element => {
                if (element.getComponent(HoleAction)) {
                    element.active = false;
                }
            });
            //修改图颜色，黑色吧  
            this.set_img("000000", 150);
            this.lock.active = true;

        } else {
            this.isLocked = false;
            //隐藏 hole
            this.node.children.forEach(element => {
                if (element.getComponent(HoleAction)) {
                    element.active = true;
                }
            });
            this.lock.active = false;
        }
    }

    touch_start(e: EventTouch) {
        AudioMgr.ins.playSound(Clips.btn_1);

        console.log("c:" , this.isLocked)
        if (!this.isLocked) {

            return;
        }

        this.set_lock_unlock(false);

        this.into_scence(new Vec2(0,400));

        // AudioMgr.ins.playSound(Clips.btn_1);

        //this.set_lock_unlock(this.isLocked);
    }


    private get_hole_arr(): Node[] {
        let hole_arr = [];
        this.node.children.forEach(element => {
            if (element.getComponent(HoleAction)) {
                hole_arr.push(element);
            }
        });
        return hole_arr;
    }

    public get_pin_num(): number {
        let pin_num = 0;
        this.node.children.forEach(element => {
            if (element.getComponent(PinAction)) {
                pin_num++;
            }
        });
        return pin_num;
    }


    public check_able_put(pin: PinAction): boolean {
        if (!this.cat_color) {
            return false;
        }
        if (this.isLocked) {
            return false;
        }
        if (pin.pin_color.id != this.cat_color.id) {
            return false;
        }
        let temp = this.get_temp_hole_num()
        if (temp > 0) {
            return true;
        } else {
            return false;
        }
    }

    //get temp hole num
    public get_temp_hole_num(): number {
        let pin_num = this.get_pin_num();
        let hole_arr = this.get_hole_arr();
        return hole_arr.length - pin_num;
    }

    private get_temp_position(): Vec3 {
        //钉子数量
        let pin_num = this.get_pin_num();
        let hole_arr = this.get_hole_arr();
        if (this.get_temp_hole_num() <= 0) {
            //钉子满了
            return null;
        }
        let target_hole_index = pin_num;

        return hole_arr[target_hole_index].position;
    }


    /** 放入电池 */
    public put_pin(pin: PinAction, path: String): boolean {
        //console.log("放入电池仓")

        let target_hole_pos = this.get_temp_position();
        if (!target_hole_pos) {
            // 没找到孔的点
            // console.log("没找到孔的点");
            return false;
        }
        //
        let world_pos = pin.node.getWorldPosition();
        let target = this.node.getComponent(UITransform).convertToNodeSpaceAR(world_pos);
        this.node.addChild(pin.node);
        pin.node.setPosition(target);

        console.log("up")
        //旋转电池，放入下面孔
        pin.img_sprite.node.setWorldRotation(math.quat(0,0,0,1));

        // let target = find("Canvas").getComponent(UITransform).convertToNodeSpaceAR(hole_world_pos);
        pin.remove_collider();

        //这里限制一下，防止多个钉子一起放进来，都执行结束动作，只准许最后一个钉子完成后执行结束动作
        let run_completed = false;
        if (this.get_temp_hole_num() <= 0) {
            run_completed = true;
        }

        
        //console.log('移动到电池仓',target_hole_pos)
        //电池飞向目标位置仓
        let temp_pos = target_hole_pos.clone();
        temp_pos.y += Global.offoset_y;
        tween(pin.node)
            .to(0.35, { position: {value: temp_pos}, scale:{value: Global.battery_scale} }, { easing: 'quadInOut' })
            .call(() => {
                //
                AudioMgr.ins.playSound(Clips.close_screw);
                if (run_completed) {
                    //如果已经满了。
                    this.full_complete(path + ">>put_pin");
                }
            })
            .start();
        return true;
    }

    /** 仓满了，移动更新 */
    private full_complete(path: String) {

        //获取奖励
        // Global.coins_action.put_coins(this.get_pin_num(), this.node.getWorldPosition());
        
        //---> 填装炮弹
        let pos =this.node.getPosition();
        pos.add(this.node.parent.getPosition());
        
        director.emit(FishEvent.addCannon, pos , this.indexSpr)
        //CannonControl.Inst.onFillConnon(pos , this.indexSpr);
        //--------------

        //电池仓移动位置
        this.node.setParent(gameMgr.Inst.layer_down_node)
        let to_position = this.node.getPosition().clone();
        to_position.y = -100;
        tween(this.node)
            .to(0.3, { position: to_position }, { easing: 'quadInOut' })
            .call(() => {
                AudioMgr.ins.playSound(Clips.complete_1);
                this.cat_color = null;
                Global.pin_prgress_computed(this.get_pin_num());
                this.clear_pins();
                director.emit(events.check_completed, this);

            }).start();
    }

    public clear_pins() {
        Tools.clearFromParent(this.node, PinAction);
    }

    private set_img(c: any, a: number) {
        let img = this.node.getChildByName("img").getComponent(Sprite);
        // img.color = color( c.color );
        this.indexSpr = c.id - 10001;
        img.spriteFrame = Global.boxImgs[this.indexSpr];
    }

    /** 倒完电池，更新电池仓 */
    public into_scence(pos: Vec2= new Vec2(0, 0)) {//-600 , 0
        // console.log('into_scence')
        if (this.isLocked) {
            //默认有锁定的，让其出现在默认位置
            this.node.setPosition(this.default_position.x, this.default_position.y);
            return;
        }
        //set slot color

        // 改 25.7.9.18.11 更新
        // switch (Global.cur_lvl_index) {
        //     case 1:
        //         this.cat_color = CatColorRules.get_next_cat_color(CatColorRules.r_0());
        //         break;
        //     case 2:
        //         this.cat_color = CatColorRules.get_next_cat_color(CatColorRules.r_0());
        //         break;
        //     case 3:
        //         this.cat_color = CatColorRules.get_next_cat_color(CatColorRules.r_1());
        //         break;
        //     case 4:
        //         this.cat_color = CatColorRules.get_next_cat_color(CatColorRules.r_2());
        //         break;
        //     case 5:
        //         this.cat_color = CatColorRules.get_next_cat_color(CatColorRules.r_3());
        //         break;
        //     default:
        //         this.cat_color = CatColorRules.get_next_cat_color(CatColorRules.r_4());
        // }

        LayerCatAction.Inst.layer_pinNum();
        this.cat_color = LayerCatAction.Inst.batteryBoxs[0];
        LayerCatAction.Inst.batteryBoxs.splice(0,1)

        console.log("显示仓：",this.cat_color)

        if (!this.cat_color) {
            //没有颜色了。
            return;
        }
        //console.log("into_scence ---->>>>>>>>> remain cat>>", CatColorRules.cat_color_arr.length);
        
        // console.log(this.cat_color)
        //set color
        this.set_img(this.cat_color, 255);

        //移动回来，飞到了自己的位置
        //this.node.setPosition(this.default_position.x + pos.x, this.default_position.y + pos.y);
        tween(this.node)
            .to(0.3, { position: this.default_position.clone() }, { easing: 'quadInOut' })
            .call(() => {
                let pin_arr: PinAction[] = [];

                // bucket
                Global.bucket_action.get_pin_arr_by_color_id(this.cat_color.id, pin_arr);
                Global.layer_empty_action.get_pin_by_color(this.cat_color.id, pin_arr);
                pin_arr.forEach(element => {
                    if (this.check_able_put(element)) {
                        this.put_pin(element, "into_scence");
                    }
                });

                this.node.setParent(LayerCatAction.Inst.node)
            })
            .start();
    }
}

